﻿using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Request;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.IC;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Casamiel.Application.Commands
{
    /// <summary>
    /// 蛋糕订单预览
    /// </summary>
    public sealed  class CakeOrderPreviewCommandHandler:BaseCommandHandler, IRequestHandler<CakeOrderPreviewCommand, BaseResult<CakeOrderPreviewReponse>>
	{
    private readonly IMemberRepository _memberRepository;
    private readonly IMemberCouponRepository _memberCouponRepository;
    private readonly IMbrStoreRepository _mbrStoreRepository;
    public CakeOrderPreviewCommandHandler(IMemberRepository memberRepository, IMbrStoreRepository mbrStoreRepository, IMemberCouponRepository memberCouponRepositor, INetICService netICService,
        IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)

    {
        _memberRepository = memberRepository;
        _memberCouponRepository = memberCouponRepositor;
        _mbrStoreRepository = mbrStoreRepository;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task<BaseResult<CakeOrderPreviewReponse>> Handle(CakeOrderPreviewCommand request, CancellationToken cancellationToken)
    {
        if (request is null)
        {
            throw new ArgumentNullException(nameof(request));
        }

         

        var storeInfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
        if (storeInfo == null)
        {
            return new BaseResult<CakeOrderPreviewReponse>(null, 9999, "门店信息有误");
        }
            decimal Discount = 0;

            var OrderAmount = request.Price * request.GoodsQuantity;
        
        var entity = await _memberRepository.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
        if (entity == null)
        {
            return new BaseResult<CakeOrderPreviewReponse>(null, 9999, "会员不存在");
        }

        if (request.DiscountList != null && request.DiscountList.Any())
        {
            decimal ticketInfoPrice;
            ICResult ticketLimit;
            if (request.DiscountList.Count > 1)
            {
                return new BaseResult<CakeOrderPreviewReponse>(null, 9999, "券只能用一张");
            }
            if (request.DiscountList[0].DiscountCouponType == 1)
            {
                
                var ticketreq = new GetTicticketReq { Cardno = request.DiscountList[0].CardNo, Pagesize = 200, State = 2, Pageindex = 1 };
                Iclogger.Trace($"GeticticketReq:{JsonConvert.SerializeObject(ticketreq)}");
                var a = await NetICService.Geticticket(ticketreq).ConfigureAwait(false);
                if (a.code == 0)
                {
                    var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
                    var ticket = list.Tickets.SingleOrDefault(t => t.Ticketid == request.DiscountList[0].DiscountCouponId);
                    if (ticket != null)
                    {
                        request.DiscountList[0].DiscountCouponMoney = ticket.Je.ToDecimal(0);
                        ticketInfoPrice = request.DiscountList[0].DiscountCouponMoney;
                        Discount = ticketInfoPrice;
                    }
                    else
                    {

                        return new BaseResult<CakeOrderPreviewReponse>(null, -23, "优惠券不可用");
                    }

                }
                else
                {
                    return new BaseResult<CakeOrderPreviewReponse>(null, -23, "优惠券不可用");
                }
                var tt = new List<long>() { request.DiscountList[0].DiscountCouponId };
                ticketLimit = await NetICService.TicketLimit(storeInfo.RelationId, tt, 1, true).ConfigureAwait(false);
            }
            else if (request.DiscountList[0].DiscountCouponType == 2)
            {
                var memberCoupon = await _memberCouponRepository.GetKeyAsync<ICasaMielSession>(request.DiscountList[0].DiscountCouponId).ConfigureAwait(false);
                if (memberCoupon == null || memberCoupon.MID != entity.ID)
                {
                    return new BaseResult<CakeOrderPreviewReponse>(null, 9999, "券不存在");
                }
                
                var ticketInfoRsp = await NetICService.Tmticketquery(new Domain.Request.IC.TmticketqueryReq { ticketcode = memberCoupon.Ticketcode }).ConfigureAwait(false);
                if (ticketInfoRsp.code != 0)
                {

                    return new BaseResult<CakeOrderPreviewReponse>(null, ticketInfoRsp.code, ticketInfoRsp.msg);

                }
                var ticketInfo = JObject.Parse(ticketInfoRsp.content);

                ticketInfoPrice = memberCoupon.Price;

                //a.Productname = ticketInfo["productname"].ToString();
                //a.Productid = ticketInfo["productid"].ToInt64(0);
                var State = ticketInfo["state"].ToInt16(0);
                //a.Startdate = DateTime.Parse(ticketInfo["startdate"].ToString(), CultureInfo.InvariantCulture);
                //a.Enddate = DateTime.Parse(ticketInfo["enddate"].ToString(), CultureInfo.InvariantCulture);
                if (State != 3)
                {
                    return new BaseResult<CakeOrderPreviewReponse>(null, 9999, "券不可用");
                }
                var ids = new List<long> {
                                ticketInfo["productid"].ToInt64(0)
                            };
                ticketLimit = await NetICService.TicketLimit(storeInfo.RelationId, ids, 0, false).ConfigureAwait(false);
                //ticketLimit = await NetICService.TicketLimit(storeInfo.RelationId, memberCoupon.Ticketcode).ConfigureAwait(false);
            }
            else
            {
                return new BaseResult<CakeOrderPreviewReponse>(null, 9999, "券类型有误");
            }
            var rule = JsonConvert.DeserializeObject<TicketsRules>(ticketLimit.content);
            //51、当前券要求最低的单据金额，limitvalue为单据金额
            //21、券仅允许消费的产品，limitvalue 为限制的产品标识
            //215、券必须消费的产品，limitvalue 为限制的产品标识
            //216、券需要消费的产品(之一)，limitvalue 为限制的产品标识，和 215 不同，216 只需要有一种产品就可以了，如果 limitvalue 只有一种产品，则和 215 效果相同
            //22、券不允许消费的产品，limitvalue 为限制的产品标识
            Discount = ticketInfoPrice;
            var list216 = rule.Tickets.Where(c => c.Limittype == 216);
            if (list216.Any())
            {
                bool s = false;
                var list216msg = "";
                foreach (var item in list216)
                {
                    if(request.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        s = true;
                    }
                    else
                    {
                        list216msg += $"{item.Productname}{item.Limitdesc}";
                    }
                }
                if (!s)
                {
                    //list.Tickets[i].State = 0;
                    return new BaseResult<CakeOrderPreviewReponse>(null, 9999, list216msg);
                }
                Discount = ticketInfoPrice;
            }

            var list215 = rule.Tickets.Where(c => c.Limittype == 215);
            if (list215.Any())
            {
                var list215sucess = true;
                var amsg = "";
                foreach (var item in list215)
                {
                    if (request.GoodsRelationId != int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        amsg += $"{item.Productname}{item.Limitdesc}";
                        list215sucess = false;
                    }
                }
                if (!list215sucess)
                {
                    //list.Tickets[i].State = 0;
                    return new BaseResult<CakeOrderPreviewReponse>(null, 9999, amsg);
                }
                //Discount = ticketInfoPrice;
            }
            var abc = rule.Tickets;
            foreach (var item in abc)
            {
                if (item.Limittype == 51)
                {
                    var tamount = OrderAmount;

                    if (tamount < item.Limitvalue.ToDecimal(0))
                    {
                        //list.Tickets[i].State = 0;
                        return new BaseResult<CakeOrderPreviewReponse>(null, 9999, item.Limitdesc);
                    }
                    //Discount = ticketInfoPrice;
                }
                if (item.Limittype == 21)
                {
                    if(request.GoodsRelationId== int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        //list.Tickets[i].State = 0;
                        return new BaseResult<CakeOrderPreviewReponse>(null, 9999, item.Limitdesc);
                    }
                    //Discount = aa[0].Price;
                }
                if (item.Limittype == 22)
                {
                    if(request.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        //list.Tickets[i].State = 0;
                        return new BaseResult<CakeOrderPreviewReponse>(null, 9999, item.Limitdesc);
                    }
                    Discount = ticketInfoPrice;
                }
            }
        }
        var rsp = new CakeOrderPreviewReponse
        {
            Discount = Discount,
            OrderAmount = OrderAmount ,
            PayAmount = OrderAmount - Discount 
        };
        return new BaseResult<CakeOrderPreviewReponse>(rsp, 0, "");
    }
}
}
